<template>
  <div class="flex">
    <vue-header title="选择城市"></vue-header>
    <div class="alphabet">
      <div v-for="(item, index) in alphabet" :key="index"
        @click="scrollIntoView(item)"
      >{{ item }}</div>
    </div>
    <div class="flex flex-scroll" v-if="showList">
      <group v-for="(list, key) in showList" :key="key" :title="key" :ref="`list-${key}`">
        <cell v-for="(city, index) in list" :key="index" :title="city.name"
          @click.native="setCity(city)"
        ></cell>
      </group>
    </div>
  </div>
</template>

<script> 
import { Group, Cell } from 'vux'
import '@/../static/js/pinyin_dict_firstletter.js'
import '@/../static/js/pinyinUtil.js'
export default {
  components: {
    Group, Cell
  },

  data (){
    return {
      alphabet: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      cityList: null,
      showList: null,
      resourceReady: null,
    }
  },

  mounted (){
    this.$alert.loading.show()
    _locationReady.finally(this.$alert.loading.hide)
    .then(() =>{
      var data = this.$store.state.location.cityList
      this.cityList = data

      var list = {}
      this.cityList.forEach(val =>{
        var firstLetter = pinyinUtil.getFirstLetter(val.name).substring(0, 1)
        if(!list[firstLetter]) list[firstLetter] = []
        list[firstLetter].push(val)
      })

      this.showList = list
    })
  },

  methods: {
    setCity (city){
      this.$store.commit('location/write', { selected: city.id })
      this.$alert.alert('已经将城市变更为：' + city.name)
      this.$router.replace({
        name: 'index/home',
        query: { reload: true }
      })
    },

    scrollIntoView (letter){
      this.$alert.toast(letter)
      this.$refs['list-' + letter] && this.$refs['list-' + letter][0].$el.scrollIntoView()
    }
  }
}
</script>

<style lang="less" scoped>
.alphabet{
  position: fixed;
  top: 46px;
  bottom: 0;
  right: 0;
  width: 20px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  background-color: #eee;
  color: #666;
  z-index: 100;

  > div{
    height: 100% / 26;
  }
}

/deep/ .weui-cells{
  &::before{
    display: none;
  }

  &::after{
    height: 1px;
    background-color: #D9D9D9;
  }
}
</style>